<template>
  <el-dialog
    title="分配角色"
    :visible="setRoleDialog"
    width="50%"
    @close="onClose"
    @opened="onOpened"
  >
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/company.js'
import { getInfoById } from '@/api/user.js'
import { updateEmployeesRoles } from '@/api/employees.js'
export default {
  props: {
    setRoleDialog: {
      type: Boolean,
      required: true
    },
    employeesId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      checkList: [],
      roles: []
    }
  },

  created() {
    this.loadRoleList()
  },

  methods: {
    async loadRoleList() {
      const res = await getRoleList()
      const res2 = await getRoleList({ page: 1, pagesize: res.total })
      this.roles = res2.rows
    },
    // 获取当前用户的角色
    async loadUserRoles() {
      const res = await getInfoById(this.employeesId)
      this.checkList = res.roleIds
    },
    onOpened() {
      this.loadUserRoles()
    },
    // 对话框关闭
    onClose() {
      this.$emit('update:set-role-dialog', false)
      this.checkList = []
    },
    async onSave() {
      if (!this.checkList.length) return this.$message.error('请分配角色')
      await updateEmployeesRoles({
        id: this.employeesId,
        roleIds: this.checkList
      })
      this.$message.success('分配成功')
      this.onClose()
    }
  }
}
</script>

<style scoped>

</style>
